import base64
import json
import pickle

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.response_code import RETCODE


class CartsView(View):
    '''购物车'''

    def post(self, request):
        """添加购物车"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数
        if not all([sku_id, count]):
            return http.HttpResponseBadRequest('参数不全')

        # 判断id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('id不存在')

        # 判断selected是否为布尔类型
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseBadRequest('参数错误')

        # 判断登录与未登录
        user = request.user
        if user.is_authenticated:
            # 登录 redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hincrby('carts_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)

            pl.execute()
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

        else:
            # 未登录 cookie
            cart_str = request.COOKIES.get('carts')
            # 判断用户是否操作购物车
            if cart_str:
                cart_str = pickle.loads(base64.b64decode(cart_str))
            else:
                cart_str = {}

            # 判断商品是否已存在,存在叠加
            if sku_id in cart_str:
                origin_count = cart_str[sku_id]['count']
                count += origin_count

            cart_str[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 加密
            cart_str = base64.b64encode(pickle.dumps(cart_str)).decode()

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', })

            response.set_cookie('carts', cart_str, max_age=3600)

            return response

    def get(self, request):
        """购物车页面"""
        user = request.user

        # 判断用户登陆
        if user.is_authenticated:
            # 链接redis
            redis_conn = get_redis_connection('carts')
            # 获取购物车数据 hash
            redis_carts = redis_conn.hgetall('carts_%s' % user.id)
            # 是否选中 set
            redis_selected = redis_conn.smembers('selected_%s' % user.id)

            # 统一数据
            cart_str = {}

            for sku_id, count in redis_carts.items():
                cart_str[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_selected,
                }
        else:
            # 未登录用户 cookies
            cart_str = request.COOKIES.get('carts')

            # 判断
            if cart_str:
                cart_str = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_str = {}

        # 购物车
        sku_ids = cart_str.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []

        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_str.get(sku.id).get('count'),
                'selected': str(cart_str.get(sku.id).get('selected')),
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_str.get(sku.id).get('count')),
            })

        context = {
            'cart_skus': cart_skus,
        }

        return render(request, 'cart.html', context)

    def put(self, request):
        """购物车改"""

        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 参数齐全
        if not all([sku_id, count]):
            return http.HttpResponseBadRequest('参数错误')

        # sku_id存在否
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('用户不存在')

        try:
            count = int(count)
        except Exception:
            return http.HttpResponseBadRequest('参数错误')

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseBadRequest('参数错误')

        user = request.user

        # 判断登录
        if user.is_authenticated:
            # 登录
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hset('cart_%s' % user.id, sku_id, count)

            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()
            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        else:
            cart_str = request.COOKIES.get('carts')

            if cart_str:
                cart_str = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_str = {}

            cart_str[sku_id] = {
                'count': count,
                'selected': selected,
            }

            cart_str = base64.b64encode(pickle.dumps(cart_str)).decode()
            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cart_str, max_age=3600)
            return response

    def delete(self, request):
        """购物车删"""
        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('参数错误')

        user = request.user

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        else:
            cart_str = request.COOKIES.get('carts')

            if cart_str:
                cart_str = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_str = {}

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

            if sku_id in cart_str:
                del cart_str[sku_id]

                cook_cart_str = base64.b64encode(pickle.dumps(cart_str)).decode()

                response.set_cookie('carts', cook_cart_str, max_age=3600)

            return response


class CartsSelectedView(View):
    def put(self, request):

        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected')

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseBadRequest('参数错误')

        user = request.user

        if user is not None and user.is_authenticated:

            redis_conn = get_redis_connection('carts')
            cart = redis_conn.hgetall('carts_%s' % user.id)
            sku_id_list = cart.keys()

            if selected:
                redis_conn.sadd('selected_%s' % user.id, *sku_id_list)
            else:
                redis_conn.srem('selected_%s' % user.id, *sku_id_list)

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

        else:

            cart_str = request.COOKIES.get('carts')

            if cart_str is not None:
                cart_str = pickle.loads(base64.b64decode(cart_str.encode()))

                for sku_id in cart_str:
                    cart_str[sku_id]['selected'] = selected

                response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
                cookie = base64.b64encode(pickle.dumps(cart_str)).decode()
                response.set_cookie('carts', cookie, max_age=3600)

                return response


class CartsSimpleView(View):
    def get(self, request):

        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            selected = redis_conn.smembers('selected_%s' % user.id)

            cart_dict = {}

            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in selected
                }
        else:
            cart_str = request.COOKIES.get('carts')

            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        cart_sku = []
        sku_ids = cart_dict.keys()

        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_sku.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_skus': cart_sku})



